import React from "react";
import "./Login.css";
import { Button, Input, Tag, Modal, message } from "antd";
import { requestDispatch } from "../../Api/api";
import Cookie from "../../Api/cookie";
import ActiveAccount from "../../Components/ActiveAccount";
import { useDispatch } from "react-redux";

function Login() {
  const [uid, setUid] = React.useState("");
  const [account, setAccount] = React.useState("chengdaya");
  const [password, setPassword] = React.useState("123456");
  const [isShowModal, setIsShowModal] = React.useState(false);
  const dispatch = useDispatch(); // 获取 dispatch 函数
  const ShowModal = () => {
    setIsShowModal(true);
  };
  const handleOk = () => {
    setIsShowModal(false);
  };
  const handleCancel = () => {
    setIsShowModal(false);
  };
  const Login = async () => {
    let res = await requestDispatch(
      dispatch,
      "/login/login",
      { account, password },
      "POST",
      {}
    );
    if (res.code >= 0) {
      //跳转到主页(储存令牌)
      Cookie.set("token", res.data.token);
      Cookie.set("uid", res.data.uid);
      window.location.href = "/";
    } else {
      if (res.data && res.data.needActive) {
        //显示激活模态框
        setUid(res.data.uid);
        ShowModal();
      }
      message.error(res.message);
    }
  };
  return (
    <div className="fill login-background">
      <div className="login-box">
        <div className="form-title">用户登录</div>
        <div className="form-item">
          <Tag color="cyan">账号</Tag>
          <Input
            value={account}
            onChange={(event) => {
              setAccount(event.target.value);
            }}
            placeholder="account"
            allowClear
          ></Input>
        </div>
        <div className="form-item">
          <Tag color="cyan">密码</Tag>
          <Input.Password
            value={password}
            onChange={(event) => {
              setPassword(event.target.value);
            }}
            placeholder="password"
            allowClear
          ></Input.Password>
        </div>
        <div className="form-item">
          <Button block type="primary" onClick={Login}>
            登录
          </Button>
        </div>
      </div>
      <Modal
        open={isShowModal}
        okText="激活"
        cancelText="取消"
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
      >
        <ActiveAccount uid={uid} onClose={() => setIsShowModal(false)} />
      </Modal>
    </div>
  );
}
export default Login;
